package com.example.blog.modules.user.service.impl;

import com.example.blog.modules.user.dto.OAuth2UserInfo;
import com.example.blog.modules.user.dto.UserDTO;
import com.example.blog.modules.user.entity.User;
import com.example.blog.modules.user.repository.UserRepository;
import com.example.blog.modules.user.service.OAuth2UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class OAuth2UserServiceImpl implements OAuth2UserService {
    
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    
    @Override
    @Transactional
    public UserDTO processOAuth2User(OAuth2UserInfo oAuth2UserInfo) {
        Optional<User> userOptional = userRepository.findByEmail(oAuth2UserInfo.getEmail());
        
        User user;
        if (userOptional.isPresent()) {
            user = userOptional.get();
            // 更新现有用户的OAuth2信息
            user.setProviderId(oAuth2UserInfo.getId());
            user.setProvider(oAuth2UserInfo.getProvider());
            if (user.getNickname() == null) {
                user.setNickname(oAuth2UserInfo.getName());
            }
            if (user.getAvatar() == null) {
                user.setAvatar(oAuth2UserInfo.getAvatar());
            }
        } else {
            // 创建新用户
            user = createOAuth2User(oAuth2UserInfo);
        }
        
        return convertToDTO(userRepository.save(user));
    }
    
    @Override
    public OAuth2UserInfo getOAuth2UserInfo(String provider, Map<String, Object> attributes) {
        OAuth2UserInfo userInfo = new OAuth2UserInfo();
        
        if ("github".equals(provider)) {
            userInfo.setId(attributes.get("id").toString());
            userInfo.setName((String) attributes.get("name"));
            userInfo.setEmail((String) attributes.get("email"));
            userInfo.setAvatar((String) attributes.get("avatar_url"));
            userInfo.setProvider("github");
        }
        
        return userInfo;
    }
    
    private User createOAuth2User(OAuth2UserInfo userInfo) {
        User user = new User();
        user.setEmail(userInfo.getEmail());
        user.setUsername(generateUsername(userInfo.getName()));
        user.setNickname(userInfo.getName());
        user.setPassword(passwordEncoder.encode(UUID.randomUUID().toString()));
        user.setProviderId(userInfo.getId());
        user.setProvider(userInfo.getProvider());
        user.setAvatar(userInfo.getAvatar());
        user.setEmailVerified(true);
        user.setRoles(Collections.singleton("USER"));
        return user;
    }
    
    private String generateUsername(String name) {
        String baseUsername = name.toLowerCase().replaceAll("[^a-z0-9]", "");
        String username = baseUsername;
        int counter = 1;
        
        while (userRepository.existsByUsername(username)) {
            username = baseUsername + counter++;
        }
        
        return username;
    }
    
    private UserDTO convertToDTO(User user) {
        UserDTO dto = new UserDTO();
        dto.setId(user.getId());
        dto.setUsername(user.getUsername());
        dto.setEmail(user.getEmail());
        dto.setNickname(user.getNickname());
        dto.setAvatar(user.getAvatar());
        dto.setBio(user.getBio());
        dto.setRoles(user.getRoles());
        dto.setEnabled(user.isEnabled());
        dto.setEmailVerified(user.isEmailVerified());
        dto.setCreatedAt(user.getCreatedAt());
        dto.setUpdatedAt(user.getUpdatedAt());
        dto.setLastLoginTime(user.getLastLoginTime());
        return dto;
    }
} 